const { Element } = window.Slate;
function renderCustomImage(elemNode, children, editor) {
    const { src, alt = '', uuid = '', href = '', style = {}, error } = elemNode;
    const { width = '', height = '' } = style
    const selected = DomEditor.isNodeSelected(editor, elemNode) // 图片是否选中
    const imageStyle = {
        width,
        height,
    }
    const containerId = genContainerId(editor, elemNode)
    imgLocaltion.push({ id: containerId, selection: editor.selection })
    // 【注意】void node 中，renderElem 不用处理 children 。core 会统一处理。
    const vnode = h(
        `img`,
        {
            props: { contentEditable: false, src: src, }, // HTML 属性，驼峰式写法
            dataset: { href: href, uuid: uuid },
            style: imageStyle, // style ，驼峰式写法
        }
    );
    const vnode2 = h(
        `span`,
        {
            props: { contentEditable: false, }, // HTML 属性，驼峰式写法
            style: {
                position: "absolute",
                transform: "translate(-50%, -50%)",
                left: getThumbnailWdith().replace("px", "") / 2 + "px",
                width: "60px",
                bottom: "10px",
                height: "30px",
                zIndex: 999,
                backgroundSize: "contain",
                textAlign: "center",
                lineHeight: "30px",
                color: "#fff",
                background: "rgba(0,0,0,0.8)",
                borderRadius: "4px"
            }, // style ，驼峰式写法
            on: {
                click() {
                    window.android ?
                        window.android.imageEdit(href) :
                        window.webkit.messageHandlers.imageEdit.postMessage(href)
                }
            }
        },
        "编辑"
    );
    const vnode3 = h(
        `span`,
        {
            props: { contentEditable: false, }, // HTML 属性，驼峰式写法
            style: {
                position: "absolute",
                transform: "translate(-50%, -50%)",
                width: "20px",
                top: "0",
                right: "-20px",
                height: "20px",
                zIndex: 999,
                backgroundSize: "contain",
                textAlign: "center",
                lineHeight: "30px",
                background: "#D8D8D8",
                borderRadius: "50%",
                lineHeight: "20px",
                color: "#fff",
                fontSize: "14px"
            }, // style ，驼峰式写法
            on: {
                click() {
                    imgLocaltion.forEach(item => {
                        if (item.id == containerId) {
                            editor.select(item.selection)
                            setTimeout(() => {
                                SlateTransforms.removeNodes(editor, {
                                    match: n => {
                                        return DomEditor.checkNodeType(n, 'customImage')
                                    }, universal: true,
                                })
                            })
                        }
                    })

                    // const imageElmnts = SlateEditor.nodes(editor, {
                    //     match: n => {
                    //         console.log(n)
                    //         if('image' === n.type){
                    //             return true
                    //         }
                    //     }})
                    //     for (const nodeEntry of imageElmnts) {
                    //         const [node, path] = nodeEntry
                    //         console.log(node,path)
                    //     }
                }
            }
        },
        "✕"
    );
    const isDisabled = editor.isDisabled()
    if (editor.selection != null) {
        if (imgLocaltion.toString().includes(containerId)) {
            imgLocaltion.forEach(el => {
                el.id == containerId && (el.selection = editor.selection)
            });
        } else {
            imgLocaltion.push({ id: containerId, location: editor.selection })
        }
    }
    if (error) {
        return h(
            "div",
            {
                props: { id: containerId, className: "w-e-image-container w-e-selected-image-container", }, // HTML 属性，驼峰式写法
                style: { ...imageStyle, overflow: "inherit" }, // style ，驼峰式写法
            },
            [vnode, vnode3]
        )
    }
    return h(
        "div",
        {
            props: { id: containerId, className: "w-e-image-container w-e-selected-image-container", }, // HTML 属性，驼峰式写法
            style: { ...imageStyle, overflow: "inherit" }, // style ，驼峰式写法
        },
        [vnode, vnode2, vnode3]
    )

    // if (selected && !isDisabled) {
    //   // 选中，未禁用 - 渲染 resize container
    //   return renderResizeContainer(editor, elemNode, vnode, { width, height })
    // }
    // 其他，渲染普通 image container
    // return renderContainer(editor, elemNode, vnode, { width, height })
}

function parseCustomImage(elem, children, editor) {
    const $elem = $(elem)
    let href = $elem.attr('data-href') || ''
    let uuid = $elem[0].id || ''
    let fileid= $elem.attr('data-file-id')||''
    // href = decodeURIComponent(href) 
    let error = $elem.attr('data-error') || ''
    if (error != "true") {
        error = ""
    }
    return {
        type: 'customImage',
        src: $elem.attr('src') || '',
        alt: $elem.attr('alt') || '',
        href,
        uuid,
        fileid,
        error,
        style: {
            width: getStyleValue($elem, 'width'),
            height: getStyleValue($elem, 'height'),
        },
        children: [{ text: '' }], // void node 有一个空白 text
    }
}
const renderCustomImageConf = {
    type: 'customImage', // 和 elemNode.type 一致
    renderElem: renderCustomImage,
}
const parseCustomImageHtmlConf = {
    selector: 'img[data-w-e-type="customImage"]', // data-w-e-type 属性，留给自定义元素，保证扩展性
    parseElemHtml: parseCustomImage,
}
function customImageToHtml(elemNode, childrenHtml) {
    const { src, alt = '', href = '', uuid = '',fileid ='',style = {}, error } = elemNode
    const { width = '', height = '' } = style
    let styleStr = ''
    if (width) styleStr += `width: ${width};`
    if (height) styleStr += `height: ${height};`
    return `<img data-w-e-type="customImage" id="${uuid}" data-file-id='${fileid}'  src="${src}" alt="${alt}" data-href="${href}" style="${styleStr}" data-md5="${generateUUID().replace(/-/g, '')}" data-error=${error ? true : ""} />`
    // return `<img class="w-e-video-container" src="${src}" alt="${alt}" data-href="${href}" id="${blueimp_md5(href.split('/')[href.split('/').length - 1])+generateUUID()}" data-md5="${blueimp_md5(href.split('/')[href.split('/').length - 1])+generateUUID()}"  style="${styleStr}"/>`
}

const customImageHtmlConf = {
    type: 'customImage',
    elemToHtml: customImageToHtml,
}

